package com.milhouz.quizzdroid;

import android.os.CountDownTimer;
import android.os.Handler;
import android.speech.tts.TextToSpeech;
import android.widget.ProgressBar;

/**
 * Countdown
 */
public abstract class CountDown extends CountDownTimer {

	private static final long TIME_TICK_MS = 40;

	private static ProgressBar mCountDownProgressBar;
	private static long mDefinedTime;
	private static final Handler mUiThreadCallback = new Handler();

	public CountDown(ProgressBar timerProgressBar, long millisInFuture) {
		super(millisInFuture, TIME_TICK_MS);
		mDefinedTime = millisInFuture;
		mCountDownProgressBar = timerProgressBar;
		mCountDownProgressBar.setIndeterminate(false);
		mCountDownProgressBar.setMax((int) millisInFuture);

		// Update timer view
		computeTimerString(millisInFuture);
		mCountDownProgressBar.setContentDescription(mCountDownString);
	}

	public void startAfterSpeech(final TextToSpeech textToSpeech) {
		// Manage TextToSpeech
		if (textToSpeech != null) {
			// Execute countdown after speaking
			final Runnable runAfterSpeaking = new Runnable() {
				@Override
				public void run() {
					start();
				}
			};

			// Thread for updating the progress bar
			new Thread(new Runnable() {
				@Override
				public void run() {
					while (textToSpeech.isSpeaking()) {
					}
					mUiThreadCallback.post(runAfterSpeaking);
				}
			}).start();
		}
	}

	public abstract void onFinishCountdown();

	@Override
	public void onFinish() {
		mCountDownString = "0:00";
		mCountDownProgressBar.setProgress((int) mDefinedTime);
		onFinishCountdown();
	}

	@Override
	public void onTick(long millisUntilFinished) {
		computeTimerString(millisUntilFinished);
		mCountDownProgressBar.setProgress((int) (mDefinedTime - millisUntilFinished));
	}

	private static String mCountDownString = "0:00";

	private void computeTimerString(long millis) {
		int seconds = (int) (millis / 1000);
		int minutes = seconds / 60;
		seconds = seconds % 60;
		StringBuilder sb = new StringBuilder();
		if (seconds < 10) {
			mCountDownString = sb.append(minutes).append(":0").append(seconds).toString();
		} else {
			mCountDownString = sb.append(minutes).append(":").append(seconds).toString();
		}
	}
}
